package com.teaching.management.controller.api;

import com.teaching.management.entity.CourseSelection;
import com.teaching.management.entity.User;
import com.teaching.management.repository.CourseSelectionRepository;
import com.teaching.management.repository.CourseRepository;
import com.teaching.management.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 选课管理相关的REST API
 */
@RestController
@RequestMapping("/api/admin/course-selections")
public class AdminCourseSelectionRestController {

    @Autowired
    private CourseSelectionRepository courseSelectionRepository;

    @Autowired
    private CourseRepository courseRepository;

    @Autowired
    private StudentRepository studentRepository;

    /**
     * 获取所有选课记录
     */
    @GetMapping
    public ResponseEntity<?> getAllCourseSelections(HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        List<CourseSelection> courseSelections = courseSelectionRepository.findAll();
        return ResponseEntity.ok(courseSelections);
    }

    /**
     * 根据条件搜索选课记录
     */
    @GetMapping("/search")
    public ResponseEntity<?> searchCourseSelections(
            @RequestParam(value = "studentId", required = false) String studentId,
            @RequestParam(value = "courseId", required = false) String courseId,
            HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        // 创建查询条件
        CourseSelection example = new CourseSelection();
        if (studentId != null && !studentId.isEmpty()) {
            example.setStudentId(studentId);
        }
        if (courseId != null && !courseId.isEmpty()) {
            example.setCourseId(courseId);
        }

        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase();

        List<CourseSelection> courseSelections = courseSelectionRepository.findAll(Example.of(example, matcher));
        return ResponseEntity.ok(courseSelections);
    }

    /**
     * 获取单个选课记录详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getCourseSelection(@PathVariable Integer id, HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        Optional<CourseSelection> courseSelectionOpt = courseSelectionRepository.findById(id);
        if (courseSelectionOpt.isPresent()) {
            return ResponseEntity.ok(courseSelectionOpt.get());
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("选课记录不存在");
        }
    }

    /**
     * 添加新选课记录
     */
    @PostMapping
    public ResponseEntity<?> addCourseSelection(@RequestBody CourseSelection courseSelection, HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        // 检查学生是否存在
        if (!studentRepository.existsById(courseSelection.getStudentId())) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("指定的学生不存在");
        }

        // 检查课程是否存在
        if (!courseRepository.existsById(courseSelection.getCourseId())) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("指定的课程不存在");
        }

        // 检查是否已经选过该课程
        CourseSelection example = new CourseSelection();
        example.setStudentId(courseSelection.getStudentId());
        example.setCourseId(courseSelection.getCourseId());
        if (courseSelectionRepository.exists(Example.of(example))) {
            return ResponseEntity.status(HttpStatus.CONFLICT).body("该学生已经选过该课程");
        }

        CourseSelection savedCourseSelection = courseSelectionRepository.save(courseSelection);
        return ResponseEntity.status(HttpStatus.CREATED).body(savedCourseSelection);
    }

    /**
     * 更新选课记录信息
     */
    @PutMapping("/{id}")
    public ResponseEntity<?> updateCourseSelection(
            @PathVariable Integer id,
            @RequestBody Map<String, Object> requestBody,
            HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        // 检查选课记录是否存在
        Optional<CourseSelection> existingCourseSelectionOpt = courseSelectionRepository.findById(id);
        if (!existingCourseSelectionOpt.isPresent()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("选课记录不存在");
        }

        CourseSelection existingCourseSelection = existingCourseSelectionOpt.get();

        // 从请求体中获取更新的字段
        String studentId = (String) requestBody.get("studentId");
        String courseId = (String) requestBody.get("courseId");

        if (studentId == null || courseId == null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("学生ID和课程ID不能为空");
        }

        // 检查学生和课程是否存在
        if (!studentRepository.existsById(studentId)) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("指定的学生不存在");
        }
        if (!courseRepository.existsById(courseId)) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("指定的课程不存在");
        }

        // 当更新到不同的学生+课程组合时，检查是否存在冲突
        if (!studentId.equals(existingCourseSelection.getStudentId()) ||
                !courseId.equals(existingCourseSelection.getCourseId())) {

            CourseSelection example = new CourseSelection();
            example.setStudentId(studentId);
            example.setCourseId(courseId);

            if (courseSelectionRepository.exists(Example.of(example))) {
                return ResponseEntity.status(HttpStatus.CONFLICT).body("该学生已经选过该课程");
            }
        }

        // 更新选课记录
        existingCourseSelection.setStudentId(studentId);
        existingCourseSelection.setCourseId(courseId);

        // 更新状态
        if (requestBody.containsKey("status")) {
            existingCourseSelection.setStatus((String) requestBody.get("status"));
        }

        // 更新成绩
        if (requestBody.containsKey("score")) {
            Object scoreObj = requestBody.get("score");
            if (scoreObj != null) {
                if (scoreObj instanceof Number) {
                    existingCourseSelection.setScore(new java.math.BigDecimal(scoreObj.toString()));
                } else if (scoreObj instanceof String && !((String) scoreObj).isEmpty()) {
                    try {
                        existingCourseSelection.setScore(new java.math.BigDecimal((String) scoreObj));
                    } catch (NumberFormatException e) {
                        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("成绩格式不正确");
                    }
                } else {
                    existingCourseSelection.setScore(null);
                }
            } else {
                existingCourseSelection.setScore(null);
            }
        }

        // 更新学年
        if (requestBody.containsKey("year")) {
            Object yearObj = requestBody.get("year");
            if (yearObj instanceof Number) {
                existingCourseSelection.setYear(((Number) yearObj).intValue());
            } else if (yearObj instanceof String && !((String) yearObj).isEmpty()) {
                try {
                    existingCourseSelection.setYear(Integer.parseInt((String) yearObj));
                } catch (NumberFormatException e) {
                    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("学年格式不正确");
                }
            }
        }

        // 更新学期
        if (requestBody.containsKey("semester")) {
            existingCourseSelection.setSemester((String) requestBody.get("semester"));
        }

        try {
            CourseSelection updatedCourseSelection = courseSelectionRepository.save(existingCourseSelection);
            return ResponseEntity.ok(updatedCourseSelection);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("更新选课记录失败: " + e.getMessage());
        }
    }

    /**
     * 删除选课记录
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteCourseSelection(@PathVariable Integer id, HttpSession session) {
        // 验证用户是否是管理员
        User user = (User) session.getAttribute("user");
        if (user == null || !"管理员".equals(user.getRole())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("未授权");
        }

        // 检查选课记录是否存在
        if (!courseSelectionRepository.existsById(id)) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("选课记录不存在");
        }

        courseSelectionRepository.deleteById(id);
        return ResponseEntity.ok().build();
    }
}